<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/12/6/006
 * Time: 11:27
 */

namespace app\api\model;


use app\api\service\Token;
use app\lib\exception\PatternMasterException;

class PatternMaster extends BaseModel {


    protected $hidden = ['update_time','create_time', 'province', 'city', 'area'];

    /**
     * 省
     * @return \think\model\relation\belongsTo
     */
    public function regionProvince() {
        return $this->belongsTo('Region', 'province', 'region_id');
    }

    /**
     * 市
     * @return \think\model\relation\belongsTo
     */
    public function regionCity() {
        return $this->belongsTo('Region', 'city', 'region_id');
    }

    /**
     * 区
     * @return \think\model\relation\belongsTo
     */
    public function regionArea() {
        return $this->belongsTo('Region', 'area', 'region_id');
    }

    /**
     * 量体师账户信息
     * @return \think\model\relation\belongsTo
     */
    public function patternMasterMember() {
        return $this->belongsTo('Member');
    }

    /**
     * 量体师所属门店信息
     * @return \think\model\relation\belongsTo
     */
    public function patternMasterShop() {
        return $this->belongsTo('Shop');
    }

    /**
     * 新增或者更新量体师申请
     * @param $param
     * @return bool
     * @throws PatternMasterException
     */
    public static function createOrUpdatePatternMaster($param) {
        $uid = Token::getCurrentUid();
        $pattern_master = self::get(['member_id' => $uid]);

        if ($pattern_master) {
            if ($pattern_master['status'] == 2) {
                throw new PatternMasterException([
                    'msg' => '您已经是量体师，请勿重复申请 ',
                    'errorCode' => 13002
                ]);
            }
            $param['status'] = 1;  // 有可能是审核失败后重新提交，所以重置状态
            $pattern_master->save($param);
        } else {
            $param['member_id'] = $uid;
            self::create($param);
        }
        return true;
    }

    /**
     * 获取用户量体师数据
     * @return array|null|\think\Model
     */
    public static function getPatternMasterInfo() {
        $uid = Token::getCurrentUid();
        $pattern_master = self::get(['member_id' => $uid], ['patternMasterMember.memberRoleInfo', 'regionProvince', 'regionCity', 'regionArea']);
        if (!$pattern_master) {
            return ['status' => 0];
        }
        $pattern_master->pattern_master_member->visible(['member_role_info'])->member_role_info->visible(['headimgurl', 'nickname']);
        return $pattern_master;
    }

}